//
//  CustomCollectionViewLayout.m
//  UI15-Homework
//
//  Created by dllo on 16/8/3.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CustomCollectionViewLayout.h"

@interface CustomCollectionViewLayout ()
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *attributesArr;
@property (nonatomic, assign) CGFloat contentWidth;
@end

@implementation CustomCollectionViewLayout

- (instancetype)init {
    self = [super init];
    if (self) {
        _attributesArr = [NSMutableArray array];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        _attributesArr = [NSMutableArray array];
    }
    return self;
}

- (void)prepareLayout {
    self.contentWidth = 0;
    CGFloat margin = 5;
    CGFloat width = 0;
    CGFloat x = 0;
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        x = x + width + margin;
        CGFloat y = 0;
        CGFloat height = CGRectGetHeight(self.collectionView.bounds);
        width = [self.delegate collectionView:self.collectionView layout:self height:height widthForItemAtIndexPath:indexPath];
        attributes.frame = CGRectMake(x, y, width, height);
        _contentWidth = x + width ;
        [_attributesArr addObject:attributes];
    }
}

- (CGSize)collectionViewContentSize {
    return CGSizeMake(_contentWidth, 0);
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return _attributesArr;
}
@end
